package com.huaxinkaiye.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.huaxinkaiye.R;
import com.huaxinkaiye.application.HuaXinApplication;
import com.huaxinkaiye.utils.MySharedPreferences;
import com.huaxinkaiye.utils.ProgressUtil;
import com.huaxinkaiye.utils.SimpleClient;
import com.huaxinkaiye.utils.ToastUtil;
import com.huaxinkaiye.utils.UrlUtils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
	private EditText username, password;
	private ImageView im_login;
	public ProgressUtil progress;
	public CheckBox im_checkbox;
	public List<NameValuePair> params;
	public Boolean Ischeck = false;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				JiexiData(msg.obj.toString());
				break;
			case 2:
				JiexiData2(msg.obj.toString());
				break;
			case 3:
				JiexiRole(msg.obj.toString());
				break;

			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		progress = new ProgressUtil(this, "正在获取数据");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		initView();
	}

	protected void JiexiRole(String s) {
		// TODO Auto-generated method stub
		Log.e("role=--", s);
		if (!s.equals("")) {
			// if(roles.contains("车辆建档")){
			// mCurTabId=R.id.channel1;
			// }else if(roles.contains("车辆初检")){
			// mCurTabId=R.id.channel2;
			// }else if(roles.contains("入场管理")){
			// mCurTabId=R.id.channel3;
			// }else if(roles.contains("拆解管理")){
			// mCurTabId=R.id.channel4;
			// }else if(roles.contains("议价申请")||roles.contains("议价审核")){
			// mCurTabId=R.id.channel5;
			// }
			if (s.contains("车辆建档") || s.contains("车辆初检") || s.contains("入场管理")
					|| s.contains("拆解管理") || s.contains("议价申请")
					|| s.contains("议价审核")) {
				Intent intent = new Intent(LoginActivity.this,
						MainActivity.class);
				intent.putExtra("roles", s);
				startActivity(intent);
				finish();
			} else {
				ToastUtil.show(this, "您没有权限登录");
			}
		}
	}

	protected void JiexiData2(String s) {
		// TODO Auto-generated method stub
		progress.dismiss();
		JSONObject json;
		try {
			json = new JSONObject(s);
			if (json.getBoolean("isSuccess")) {
				MySharedPreferences.getInstance(this).setString("account",
						username.getText().toString());
				if (Ischeck) {
					MySharedPreferences.getInstance(this).setString("password",
							password.getText().toString());
				}
				getUserRole(json.getInt("id"));
				// finish();
			} else {
				ToastUtil.show(LoginActivity.this, json.getString("message"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getUserRole(int i) {
		// TODO Auto-generated method stub
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", i + ""));
		final Map map = new HashMap();
		map.put("id", i);
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				try {
					String data = SimpleClient
							.doGet(UrlUtils.userrole_url, map);
					Message message = new Message();
					message.what = 3;
					message.obj = data;
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}.start();
	}

	protected void JiexiData(String s) {
		// TODO Auto-generated method stub
		JSONObject json;
		try {
			json = new JSONObject(s);
			if (json.getBoolean("isSuccess")) {
				MySharedPreferences.getInstance(LoginActivity.this).setString(
						"loginType", json.getInt("loginType") + "");
				login2(json.getInt("loginType"));
			} else {
				progress.dismiss();
				ToastUtil.show(LoginActivity.this, json.getString("message"));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			progress.dismiss();
			e.printStackTrace();
		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		username = (EditText) findViewById(R.id.ed_username);
		username.setText(MySharedPreferences.getInstance(this).getString(
				"account"));
		password = (EditText) findViewById(R.id.ed_password);
		password.setText(MySharedPreferences.getInstance(this).getString(
				"password"));
		im_login = (ImageView) findViewById(R.id.im_login);
		im_login.setOnClickListener(this);
		im_checkbox = (CheckBox) findViewById(R.id.im_checkbox);
		im_checkbox.setChecked(MySharedPreferences.getInstance(this)
				.getBoolean("ischeck"));
		im_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				// Ischeck = arg1;
				MySharedPreferences.getInstance(LoginActivity.this).setBoolean(
						"ischeck", arg1);
				if (arg1) {
					MySharedPreferences.getInstance(LoginActivity.this)
							.setString("password",
									password.getText().toString());
				} else {
					MySharedPreferences.getInstance(LoginActivity.this)
							.setString("password", "");
				}
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.im_login:
			Login();
			break;
		}

	}

	private void Login() {
		// TODO Auto-generated method stub
		if (HuaXinApplication.isNetWorkConnected()) {
			if (username.getText().toString().equals("")
					|| password.getText().toString().equals("")) {
				ToastUtil.show(this, "用户名或密码不为空！");
				return;
			}
			progress.show();
			final String url = UrlUtils.login_url_before + "account="
					+ username.getText().toString();
			Log.e("login_url", url);
			params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("account", username.getText()
					.toString()));
			// params.add(new BasicNameValuePair("password", password.getText()
			// .toString()));
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					try {
						String data = SimpleClient.doPost(
								UrlUtils.login_url_before, params);
						Log.e("data", data);
						Message mes = new Message();
						mes.what = 1;
						mes.obj = data;
						handler.sendMessage(mes);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						progress.dismiss();
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
		}

		// if (HuaXinApplication.isNetWorkConnected()) {
		//
		// new AsyncTaskUtil() {
		// @Override
		// public void doJSON(String s) {
		// // TODO Auto-generated method stu
		// Log.e("login_data", s);
		// try {
		// JSONObject json = new JSONObject(s);
		// if (json.getBoolean("isSuccess")) {
		// MySharedPreferences.getInstance(LoginActivity.this)
		// .setString("loginType",
		// json.getInt("loginType") + "");
		// login2(json.getInt("loginType"));
		// } else {
		// progress.dismiss();
		// ToastUtil.show(LoginActivity.this,
		// json.getString("message"));
		// }
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// progress.dismiss();
		// e.printStackTrace();
		// }
		//
		// }
		// }.execute(url);
		// } else {
		// Toast.makeText(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT)
		// .show();
		// }

		// if (HuaXinApplication.isNetWorkConnected()) {
		// progress.show();
		// new PostTaskUtil(this) {
		// @Override
		// public void callBack(String re) {
		// // TODO Auto-generated method stub
		// Log.e("login_data", re);
		// try {
		// JSONObject json = new JSONObject(re);
		// if (json.getBoolean("isSuccess")) {
		// MySharedPreferences.getInstance(LoginActivity.this)
		// .setString("loginType",
		// json.getInt("loginType") + "");
		// login2(json.getInt("loginType"));
		// } else {
		// progress.dismiss();
		// ToastUtil.show(LoginActivity.this,
		// json.getString("message"));
		// }
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }
		// }.execute(UrlUtils.login_url_before, "account", username.getText()
		// .toString());
		// } else {
		// Toast.makeText(LoginActivity.this, "网络异常", Toast.LENGTH_SHORT)
		// .show();
		// }
	}

	protected void login2(int loginType) {
		// TODO Auto-generated method stub
		// new PostTaskUtil(this) {
		//
		// @Override
		// public void callBack(String re) {
		// // TODO Auto-generated method stub
		// Log.e("login_data2", re);
		// try {
		// JSONObject json = new JSONObject(re);
		// if (json.getBoolean("isSuccess")) {
		// ToastUtil.show(LoginActivity.this,
		// json.getString("message"));
		// Intent intent = new Intent(LoginActivity.this,
		// FristPageActivity.class);
		// startActivity(intent);
		// finish();
		// } else {
		// ToastUtil.show(LoginActivity.this,
		// json.getString("message"));
		// }
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// }.execute(UrlUtils.login_url2,"account"
		// ,username.getText().toString(),"password"
		// , password.getText().toString(),"loginType",loginType+""
		// , "digest" , "" , "iaguid" ,"");
		// progress.dismiss();
		String url2 = UrlUtils.login_url2 + "account="
				+ username.getText().toString() + "&password="
				+ password.getText().toString() + "&loginType=" + loginType
				+ "&digest=" + "" + "&iaguid=" + "";
		Log.e("login_url2", url2);

		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("account", username.getText()
				.toString()));
		params.add(new BasicNameValuePair("password", password.getText()
				.toString()));
		params.add(new BasicNameValuePair("loginType", loginType + ""));
		params.add(new BasicNameValuePair("digest", ""));
		params.add(new BasicNameValuePair("iaguid", ""));
		new Thread() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				String data;
				try {
					data = SimpleClient.doPost(UrlUtils.login_url2, params);
					Log.e("data2", data);
					Message mes = new Message();
					mes.what = 2;
					mes.obj = data;
					handler.sendMessage(mes);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					progress.dismiss();
					e.printStackTrace();
				}
			}
		}.start();

		// new AsyncTaskUtil() {
		//
		// @Override
		// public void doJSON(String s) {
		// // TODO Auto-generated method stub
		// Log.e("login_data2", s);
		// try {
		// JSONObject json = new JSONObject(s);
		// if (json.getBoolean("isSuccess")) {
		// ToastUtil.show(LoginActivity.this,
		// json.getString("message"));
		// Intent intent = new Intent(LoginActivity.this,
		// FristPageActivity.class);
		// startActivity(intent);
		// finish();
		// } else {
		// ToastUtil.show(LoginActivity.this,
		// json.getString("message"));
		// }
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }
		// }.execute(url2);
	}

}
